package com.android.binderserverclient0.workmanager

import android.annotation.SuppressLint
import android.content.Context
import androidx.annotation.WorkerThread
import androidx.work.ForegroundInfo
import androidx.work.ListenableWorker
import androidx.work.WorkerParameters
import androidx.work.impl.utils.futures.SettableFuture
import androidx.work.workDataOf
import com.google.common.util.concurrent.ListenableFuture

class DefineWorker(context: Context, workerParameters: WorkerParameters) : ListenableWorker(context, workerParameters) {

    private lateinit var mFuture: SettableFuture<Result>

    @SuppressLint("RestrictedApi")
    override fun startWork() : ListenableFuture<Result> {
        mFuture = SettableFuture.create()
        backgroundExecutor.execute {
            try {
                val result = Result.success(
                    workDataOf(
                        "123" to 456,
                        "789" to 110,
                        "abc" to 120,
                        "def" to 320
                    )
                )
                mFuture.set(result)
            } catch (throwable: Throwable) {
                mFuture.setException(throwable)
            }
        }
        return mFuture
    }

    @SuppressLint("RestrictedApi")
    override fun getForegroundInfoAsync() : ListenableFuture<ForegroundInfo> {
        val mFuture = SettableFuture.create<ForegroundInfo>()
        backgroundExecutor.execute {
            try {
                val mForegroundInfo = getForegroundInfo()
                mFuture.set(mForegroundInfo)
            } catch (throwable : Throwable) {
                mFuture.setException(throwable)
            }
        }
        return mFuture
    }

    @WorkerThread
    fun getForegroundInfo() : ForegroundInfo {
        throw IllegalStateException("Expedited WorkRequests require a Worker to " + "provide an implementation for \n `getForegroundInfo()`")
    }
}